import globalConstant from '../../common/global-constant'

const path = require('path')
const fs = require('fs')

function getFullPath(relativePath) {
    return `${process.cwd()}\\${globalConstant.DATA_FILE_PRE}${!!relativePath ? `\\${relativePath}` : ''}`
}

function checkFileIsExit(fullPath, create = false, isThrowError = true) {
    try {
        fs.statSync(fullPath)
    } catch (e) {
        if (e.message.indexOf('no such file or directory') > 0) {
            if (create) {
                let prePath = fullPath.substr(0, fullPath.lastIndexOf('\\'))
                try {
                    fs.statSync(prePath)
                } catch (e) {
                    if (e.message.indexOf('no such file or directory') > 0) {
                        checkFileIsExit(prePath, true)
                    } else {
                        throw new Error(`文件操作异常:${prePath} 不存在! `)
                    }
                }
                fs.mkdirSync(fullPath)
            } else {
                throw new Error(`文件操作异常:${fullPath} 不存在! `)
            }
        } else {
            throw e
        }
    }
    return true
}

export default {
    fileWrite: (relativePath, fileName, content) => {

        let fullPath = getFullPath(relativePath)
        checkFileIsExit(fullPath, true)
        fs.writeFileSync(`${fullPath}\\${fileName}`, content)
    },
    fileAppendWrite: (relativePath, fileName, content) => {
        let fullPath = getFullPath(relativePath)
        checkFileIsExit(fullPath, true)
        fs.appendFileSync(relativePath, content)
    },
    fileRead: async (relativePath, fileName) => {
        let fullPath = getFullPath(relativePath)
        checkFileIsExit(fullPath)
        return fs.readFileSync(relativePath)
    },
    getFileByPath: (relativePath) => {
        let fullPath = getFullPath(relativePath)
        try {
            let fileNameList = fs.readdirSync(fullPath).map(p => `${fullPath}\\${p}`)
            let res = []
            for (let file of fileNameList) {
                let data = {
                    content: fs.readFileSync(file).toString(),
                    filePath: file
                }
                res.push(data)
            }
            return res
        } catch (e) {
            return []
        }
    },
    fileRemove: (path) => {
        fs.unlinkSync(path)
    }
}
